package com.mall.product.controller;

import java.util.Arrays;
import java.util.Map;

import com.mall.common.valid.AddGroup;
import com.mall.common.valid.UpdateGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.mall.product.entity.BrandEntity;
import com.mall.product.service.BrandService;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.R;


/**
 * 品牌
 *
 * @author super
 * @email 3217985254@qq.com
 * @date 2023-07-16 17:13:15
 */
@Slf4j
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = brandService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId) {
        BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    /*@RequestMapping("/save")
    public R save(@RequestBody @Valid BrandEntity brand, BindingResult bindingResult) {
        log.error("校验结果BindingResult:{}",bindingResult);
        //获取校验结果
        if (bindingResult.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            bindingResult.getFieldErrors().forEach((item)->{
                //获取校验提示信息
                String message = item.getDefaultMessage();
                //获取校验属性名称
                String field= item.getField();
                map.put(field,message);
            });
            return R.error(400,"传入参数不合法").put("data",map);
        } else {
            brandService.save(brand);

        }
        return R.ok();
    }*/
    @RequestMapping("/save")
    public R save(@RequestBody @Validated({AddGroup.class}) BrandEntity brand) {
        brandService.save(brand);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody @Validated({UpdateGroup.class}) BrandEntity brand) {
        brandService.updateBrandAndOther(brand);
//        brandService.updateById(brand);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds) {
        brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}
